<template>
  <el-row :gutter="6">
    <el-col :span="24" class="col-flex">
      <el-col class="breadcrumb-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/main' }">信息管理</el-breadcrumb-item>
          <el-breadcrumb-item>文件中心</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
      <el-col class="maincont-container">
        <div id="tableview" v-if="tableshow">
          <my-tableX
            v-loading="listloading"
            :element-loading-text="listloadingText"
            element-loading-spinner="el-icon-loading"
            tableHeight="340px"
            @dataView="viewData"
            @dataDownload="downloadFile"
            @dataEdit="editData"
            @dataDelete="deleteData"
            @dataAdd="addNewFileInfo"
            :tableData="bondsAllList"
            :configs="configs"
          ></my-tableX>
        </div>
        <div
          id="formview"
          class="data-form"
          v-if="!tableshow"
          v-loading="loading"
          element-loading-text="正在提交......"
          element-loading-spinner="el-icon-loading"
        >
          <div>
            <h5>{{operationType}}</h5>
          </div>
          <el-form
            size="small"
            style
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="文件名称" prop="filename">
              <el-input :disabled="onlyview" v-model="ruleForm.filename"></el-input>
            </el-form-item>
            <el-form-item label="文件类型" prop="filetype">
              <!-- <el-input :disabled="onlyview" v-model="ruleForm.filetype"></el-input> -->
              <el-select :disabled="onlyview" v-model="ruleForm.filetype" placeholder="请选择文件类型">
                <el-option label="技术标准" value="技术标准"></el-option>
                <el-option label="设计条件" value="设计条件"></el-option>
                <el-option label="制式表格" value="制式表格"></el-option>
                <el-option label="报告模板" value="报告模板"></el-option>
                <el-option label="制度文件" value="制度文件"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文件来源" prop="filesource">
              <el-select :disabled="onlyview" v-model="ruleForm.filesource" placeholder="请选择文件来源">
                <el-option label="建设单位" value="建设单位"></el-option>
                <el-option label="设计单位" value="设计单位"></el-option>
                <el-option label="勘察总体" value="勘察总体"></el-option>
                <el-option label="勘察单位" value="勘察单位"></el-option>
                <el-option label="咨询单位" value="咨询单位"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文件日期" prop="upload_time" required>
              <el-input disabled v-model="ruleForm.upload_time"></el-input>
            </el-form-item>
            <el-form-item label="附件">
              <el-upload
                :disabled="onlyview"
                class="upload-demo"
                ref="upload"
                action="1111"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :accept="filetype"
                :limit="5"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :file-list="fileList"
                :http-request="uploadSectionFile"
              >
                <el-button
                  v-if="!onlyview"
                  :disabled="onlyview"
                  slot="trigger"
                  size="small"
                  type="primary"
                >选取文件</el-button>
                <!-- <el-button
                  v-if="!onlyview"
                  :disabled="onlyview"
                  style="margin-left: 10px;"
                  size="small"
                  type="success"
                  @click="submitUpload"
                >上传到服务器</el-button>-->
                <div
                  v-if="!onlyview"
                  slot="tip"
                  class="el-upload__tip"
                >上传图片、文档文件，每个不超过350M，最多上传5个，请上传完后再点击提交</div>
              </el-upload>
            </el-form-item>
            <el-form-item style="text-align:right">
              <el-button v-if="!onlyview" :disabled="onlyview" type="primary" @click="submitForm">提交</el-button>
              <el-button @click="resetForm">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>

<script>
import myTableX from "@/components/base/tableX";
import { formatDate } from "@/utils/date";
import httpfile from "@/api/file/index";
import fileType from "@/config/file.type.config";
import { random } from "@/utils/random";

export default {
  components: { myTableX },
  inject: ["reload"],
  data() {
    return {
      filetype: fileType.fileCenter,
      listloadingText: "刷新中...",
      onlyview: true,
      operationType: "",
      bondsAllList: [],
      tableshow: true,
      isupdate: false,
      fileList: [],
      loading: false,
      listloading: false,
      configs: {
        columns: [
          { field: "filename", name: "文件名称", canSort: true },
          { field: "filesource", name: "文件来源", canSort: true },
          { field: "filetype", name: "文件类型", canSort: true },
          { field: "upload_time", name: "文件日期", canSort: true }
        ],
        operationCol: {
          show: true,
          view: true,
          edit: this.$store.state.m_user.userInfo.roleId <= 3,
          delete: this.$store.state.m_user.userInfo.roleId <= 3,
          download: false
        },
        showFilterRow: {
          show: true
        },
        operationBtn: {
          show: true,
          add: this.$store.state.m_user.userInfo.roleId <= 3,
          output: false
        }
      },
      ruleForm: {
        filesource: "",
        filename: "",
        filetype: "",
        url: "",
        uploadby: ""
      },
      rules: {
        filename: [
          { required: true, message: "请输入文件名称", trigger: "blur" },
          { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" }
        ],
        filetype: [
          { required: true, message: "请选择文件类型", trigger: "change" }
        ],
        filesource: [
          { required: true, message: "请选择文件来源", trigger: "change" }
        ]
      }
    };
  },

  methods: {
    beforeUpload(file) {
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (this.filetype.indexOf("." + testmsg.toLowerCase()) < 0) {
        this.$message({
          message: "上传文件格式不符合要求：" + testmsg,
          type: "warning"
        });
        return false;
      }
      return true;
      // const extension = testmsg === "xls";
      // const extension2 = testmsg === "xlsx";
      // // const isLt2M = file.size / 1024 / 1024 < 10
      // if (!extension && !extension2) {
      //   this.$message({
      //     message: "上传文件只能是 xls、xlsx格式!",
      //     type: "warning"
      //   });
      // }
    },

    uploadSectionFile(params) {
      console.log(this.fileList);
      const uid = params.file.uid;
      // ##修改##
      let URL = window.URL || window.webkitURL;
      let url = URL.createObjectURL(params.file);

      let keyname = formatDate(new Date(), "yyyyMMddhhmmss") + random();
      // ##修改##

      const fileData = new FormData();
      fileData.append("file", params.file);
      const query = {
        path:
          "/" +
          this.$store.state.projectInfo.projectName +
          "/文件中心/" +
          keyname +
          params.file.name
      };

      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          token: window.sessionStorage.getItem("token")
        },
        // 这一段代码解决进度条不显示的问题，属于 axios 的使用知识。具体可以看文末的参考链接。
        onUploadProgress: progressEvent => {
          const percentCompleted = Math.floor(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          params.onProgress({ percent: percentCompleted });
        }
      };

      httpfile.upload(query, config, fileData).then(res => {
        console.log(res);
        if (res.status == 200) {
          // ##修改##
          this.fileList.push({
            url: url,
            name: params.file.name,
            realname: keyname + params.file.name
          });
          params.onSuccess(res);
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
      this.tableshow = true;
    },

    refreshData() {
      this.tableshow = true;
      this.listloading = true;
      this.listloadingText = "刷新中...";
      this.$api.filecenter
        .getfile()
        .then(result => {
          if (result.code == 200) {
            this.bondsAllList = result.data;
            // console.log(this.bondsAllList);
            // this.$message("加载成功");
            this.listloading = false;
          }
        })
        .catch(err => {
          console.log(err);
          this.$message.error(err);
          this.listloading = false;
        });
    },

    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.isupdate) {
            this.ruleForm.url = this.fileList
              .map(item => {
                return (
                  "/" +
                  this.$store.state.projectInfo.projectName +
                  "/文件中心/" +
                  item.realname // ##修改##
                );
              })
              .join(";");
            // alert('submit!');
            console.log(this.ruleForm);
            this.loading = true;
            this.$api.filecenter
              .modify(this.ruleForm)
              .then(res => {
                this.loading = false;
                if (res.code == 200) {
                  this.$message.success("操作成功!");
                  this.tableshow = !this.tableshow;
                  this.reload();
                  //this.refreshData();
                } else {
                  this.$message.success("操作失败!" + res.msg);
                }
              })
              .catch(err => {
                this.loading = false;
                this.$message.success("操作失败!!" + err);
              });
          } else {
            this.ruleForm.url = this.fileList
              .map(item => {
                return (
                  "/" +
                  this.$store.state.projectInfo.projectName +
                  "/文件中心/" +
                  item.realname // ##修改##
                );
              })
              .join(";");
            this.loading = true;
            this.$api.filecenter
              .add(this.ruleForm)
              .then(res => {
                this.loading = false;
                if (res.code == 200) {
                  this.$message.success("操作成功!");
                  this.tableshow = !this.tableshow;
                  this.reload();
                  //this.refreshData();
                } else {
                  this.$message.success("操作失败!" + res.msg);
                }
              })
              .catch(err => {
                this.loading = false;
                this.$message.success("操作失败!!" + err);
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    addNewFileInfo() {
      this.operationType = "新增文件";
      this.isupdate = false;
      this.tableshow = false;
      this.onlyview = false;
      this.fileList = [];
      this.ruleForm = {
        uploadby: this.$store.state.m_user.userInfo.user_name,
        upload_time: this.getNowFormatDate(),
        subject_id: this.$store.state.projectInfo.projectName
      };
    },

    viewData(row) {
      console.log(row);
      this.isupdate = true;
      this.onlyview = true;
      this.tableshow = !this.tableshow;
      this.ruleForm = row;
      this.operationType = "查看文件";
      this.fileList = [];

      // ##修改##
      if (row.url != "") {
        row.url.split(";").forEach(item => {
          if (item != "") {
            let b = item.split("/");
            this.fileList.push({
              name: b[b.length - 1].slice(18),
              realname: b.slice(b.length - 1, b.length).toString(String),
              url: item
            });
          }
        });
      }
      // ##修改##
    },

    editData(row) {
      console.log(row);
      // this.$message("触发编辑事件");
      this.isupdate = true;
      this.onlyview = false;
      this.tableshow = !this.tableshow;
      this.ruleForm = row;
      this.operationType = "编辑文件";
      this.fileList = [];
      // ##修改##
      if (row.url != "") {
        row.url.split(";").forEach(item => {
          if (item != "") {
            let b = item.split("/");
            this.fileList.push({
              name: b[b.length - 1].slice(18),
              realname: b.slice(b.length - 1, b.length).toString(String),
              url: item
            });
          }
        });
      }
      // ##修改##
    },

    deleteData(row) {
      var that = this;
      console.log(row.uploadby);
      //   this.$message("触发删除事件");
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.listloading = true;
          this.listloadingText = "正在删除...";
          this.$api.filecenter
            .delete({ reqMap: row.id })
            .then(res => {
              if (res.code == 200) {
                this.listloading = false;
                this.$message.success("操作成功!");
                this.reload();
                //this.refreshData();
              } else {
                this.listloading = false;
                this.$message.success("删除失败:" + res.msg);
              }
            })
            .catch(err => {
              this.listloading = false;
              this.$message.danger("操作失败!" + err);
            });
        })
        .catch(err => {
          return;
        });
    },

    outputData() {
      this.$message("触发导出事件");
    },
    downloadFile(data) {
      console.log(data);
      this.$message("触发下载事件");
    },

    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },

    //upload功能
    submitUpload() {
      // this.$refs.
      this.$refs.upload.submit();
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      let temp = this.fileList.filter(item => {
        return item.uid != file.uid;
      });

      this.fileList = temp;
    },

    handlePreview(file) {
      window.open(file.url);
    },

    handleExceed(files, fileList) {
      this.$message.warning("最多选择 5 个文件");
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  },

  created() {
    this.ruleForm.uploadby = this.$store.state.m_user.userInfo.name;
    this.$api.filecenter
      .getfile({ reqMap: this.$store.state.projectInfo.projectName })
      .then(result => {
        if (result.code == 200) {
          this.bondsAllList = result.data;
          console.log(this.bondsAllList);
        }
      })
      .catch(err => {
        console.log(err);
        this.$message.error(err);
      });
  },

  computed: {
    url() {
      return (
        "/" +
        this.$store.state.projectInfo.projectName +
        "/" +
        "文件中心" +
        "/" +
        this.fileList[0].name
      );
    }
  }
};
</script>

<style lang="less" scoped>
.col-flex {
  padding-top: 30px;
  height: 100%;
  box-sizing: border-box;
  .breadcrumb-container {
    height: 30px;
    margin-top: -20px;
  }
  .maincont-container {
    height: calc(~"100% - 10px");
    margin-top: 3px;

    #tableview {
      height: 100%;
    }

    .data-form {
      padding: 0px 150px;

      .el-select {
        display: block;
      }

      .upload-demo {
        text-align: left;
      }
    }
  }
}
</style>